﻿namespace FluentMvc.Validations
{
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using System.Web.Mvc;

    public class RegExValidator : FluentValidator, IClientValidatable
    {
        public string Pattern { get; set; }
        public override bool Validate(FluentValidationContext context)
        {
            if (context.Value == null)
                return true;
            return Regex.IsMatch(context.Value.ToString(), Pattern);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            if (string.IsNullOrEmpty(Pattern))
                return new List<ModelClientValidationRule>();
            var rule = new ModelClientValidationRule {ValidationType = "regex",ErrorMessage = ErrorMessage};
            rule.ValidationParameters.Add("pattern", Pattern);
            return new List<ModelClientValidationRule> {rule};
        }
    }
}